<template>
  <div class="form-detail">
    <div v-if="formData" class="form-content">
      <div class="form-header">
        <h3>表单名称：{{ formData.name }}</h3>
        <div class="form-actions">
          <!-- 添加表单校验状态显示 -->
          <div class="form-validation-status">
            <el-tag 
              :type="formValidationStatus.valid ? 'success' : 'warning'"
              size="small"
            >
              <Icon :icon="formValidationStatus.valid ? 'ant-design:check-circle-outlined' : 'ant-design:exclamation-circle-outlined'" />
              {{ formValidationStatus.valid ? '表单校验通过' : '表单校验未通过' }}
            </el-tag>
          </div>
          <el-button v-if="!isStartMode && formSchema" type="primary" @click="previewForm">
            <Icon icon="ant-design:eye-outlined" />
            预览表单
          </el-button>
          <!-- 添加表单数据预览按钮 -->
          <el-button type="info" @click="showFormDataPreview = !showFormDataPreview">
            <Icon icon="ant-design:code-outlined" />
            {{ showFormDataPreview ? '隐藏' : '显示' }}数据预览
          </el-button>
          <!-- 添加手动刷新按钮 -->
          <el-button type="warning" @click="refreshFormData">
            <Icon icon="ant-design:reload-outlined" />
            刷新数据
          </el-button>
        </div>
      </div>
      
      <!-- 表单数据预览区域 -->
      <div v-if="showFormDataPreview" class="form-data-preview-section">
        <h4 class="preview-title">表单数据预览</h4>
        <div class="preview-content">
          <el-alert
            title="当前表单数据"
            description="以下数据可用于条件表达式中"
            type="info"
            show-icon
            :closable="false"
            style="margin-bottom: 15px;"
          />
          <div class="form-data-display">
            <pre>{{ JSON.stringify(formValues, null, 2) }}</pre>
          </div>
        </div>
      </div>
      
      <div class="form-preview">
        <!-- VForm3表单渲染器 -->
        <div v-if="formSchema && (isStartMode || isTaskMode)" class="form-renderer">
          <div class="form-container">
            <v-form-render
              ref="formRenderRef"
              :form-json="formSchema"
              :form-data="formValues"
              :option-data="optionData"
              @submit="handleFormSubmit"
            />
          </div>
        </div>
        
        <!-- 表单预览模式 -->
        <div v-else-if="isPreviewMode && formSchema" class="form-preview-mode">
          <div class="form-container">
            <v-form-render
              ref="formRenderRef"
              :form-json="formSchema"
              :form-data="formValues"
              :option-data="optionData"
              :readonly="true"
            />
          </div>
        </div>
        
        <!-- 查看模式（只读） -->
        <div v-else-if="formSchema && isViewMode" class="form-view-mode">
          <div class="form-container">
            <v-form-render
              ref="formRenderRef"
              :form-json="formSchema"
              :form-data="formValues"
              :option-data="optionData"
              :readonly="true"
            />
          </div>
        </div>
        
        <!-- 表单占位符（仅在没有表单数据时显示） -->
        <div v-else class="form-placeholder">
          <Icon icon="ant-design:form-outlined" />
          <p>{{ isStartMode ? '请填写表单数据' : '表单预览区域' }}</p>
          <div v-if="!formSchema" class="no-schema">
            <p>暂无表单配置信息</p>
          </div>
        </div>
      </div>
    </div>
    
    <div v-else class="no-form">
      <Icon icon="ant-design:exclamation-circle-outlined" />
      <p>暂未绑定表单</p>
    </div>
    
    <!-- 表单预览弹窗 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="表单预览"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="preview-dialog-content">
        <v-form-render
          ref="previewFormRenderRef"
          :form-json="formSchema"
          :form-data="formValues"
          :option-data="optionData"
          :readonly="true"
        />
      </div>
      <template #footer>
        <el-button @click="previewDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="startEdit">开始编辑</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import Icon from '@/components/Icon/Icon.vue'
import { VFormRender } from 'vform3-builds'

// 引入统一的夜间模式样式
import '../styles/dark-theme.css'

const props = defineProps({
  formData: {
    type: Object,
    default: null
  },
  processData: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'view', // view: 查看模式, start: 发起模式, task: 任务处理模式
    validator: (value) => ['view', 'start', 'task'].includes(value)
  },
  editable: {
    type: Boolean,
    default: false // 是否可编辑，只有start和task模式可以编辑
  }
})

const emit = defineEmits(['form-action', 'form-data-change'])

// 表单渲染器引用
const formRenderRef = ref(null)
const previewFormRenderRef = ref(null)

// 表单状态
const isPreviewMode = ref(false)
const previewDialogVisible = ref(false)

// 表单数据
const formValues = ref({})
const optionData = ref({})

// 添加表单数据预览状态
const showFormDataPreview = ref(false)

// 添加表单校验状态
const formValidationStatus = ref({
  valid: false,
  errors: []
})

// 添加定时器来同步表单数据
let formDataSyncTimer = null

// 开始表单数据同步
const startFormDataSync = () => {
  if (formDataSyncTimer) {
    clearInterval(formDataSyncTimer)
  }
  
  formDataSyncTimer = setInterval(async () => {
    if (formRenderRef.value && (isStartMode.value || isTaskMode.value)) {
      try {
        const currentFormData = await formRenderRef.value.getFormData()
        if (currentFormData && typeof currentFormData === 'object') {
          // 检查数据是否有变化
          const currentFormDataStr = JSON.stringify(currentFormData)
          const formValuesStr = JSON.stringify(formValues.value)
          const hasChanged = currentFormDataStr !== formValuesStr
          
          if (hasChanged) {
            formValues.value = currentFormData
            emit('form-data-change', currentFormData)
            
            // 更新表单校验状态
            await updateFormValidationStatus()
          }
        }
      } catch (error) {
        // 忽略获取表单数据时的错误
      }
    }
  }, 500) // 改为每500毫秒检查一次，提高响应速度
}

// 停止表单数据同步
const stopFormDataSync = () => {
  if (formDataSyncTimer) {
    clearInterval(formDataSyncTimer)
    formDataSyncTimer = null
  }
}

// 计算属性
const isStartMode = computed(() => props.mode === 'start')
const isTaskMode = computed(() => props.mode === 'task')
const isViewMode = computed(() => props.mode === 'view')
const canEdit = computed(() => props.editable && (isStartMode.value || isTaskMode.value))
const formSchema = computed(() => {
  const schema = props.formData?.formSchema || props.formData?.formDetail?.formSchema
  
  // 如果schema是字符串，尝试解析为对象
  if (typeof schema === 'string') {
    try {
      const parsedSchema = JSON.parse(schema)
      return parsedSchema
    } catch (error) {
      console.error('FormDetail - 解析formSchema失败:', error)
      return null
    }
  }
  
  // 如果已经是对象，直接返回
  if (schema && typeof schema === 'object') {
    return schema
  }
  
  return null
})

// 监听表单数据变化
watch(() => props.formData, (newFormData) => {

  if (newFormData) {
    // 检查是否是有效的表单数据对象
    if (newFormData.formData && typeof newFormData.formData === 'object') {
      // 避免重置为事件对象
      if (!newFormData.formData.target && !newFormData.formData.type) {
        formValues.value = { ...newFormData.formData }
      }
    } else if (newFormData.formData && typeof newFormData.formData === 'string') {
      // 如果是字符串，尝试解析JSON
      try {
        const parsedData = JSON.parse(newFormData.formData)
        formValues.value = parsedData

      } catch (error) {
        console.error('FormDetail - 解析表单数据失败:', error)
        formValues.value = {}
      }
    } else {
      // 如果没有formData字段，直接使用整个对象
      if (!newFormData.target && !newFormData.type) {
        formValues.value = { ...newFormData }
      }
    }
    
    // 初始化选项数据
    if (newFormData.optionData) {
      optionData.value = { ...newFormData.optionData }
    } else {
      optionData.value = {}
    }
  } else {
    // 如果没有数据，重置为空对象
    formValues.value = {}
    optionData.value = {}
  }
}, { immediate: true, deep: true })

// 预览表单
const previewForm = () => {
  isPreviewMode.value = true
  previewDialogVisible.value = true
}

// 处理表单提交
const handleFormSubmit = (formData) => {
  emit('form-action', 'submit', formData)
  emit('form-data-change', formData)
}

// 手动刷新表单数据
const refreshFormData = async () => {
  if (formRenderRef.value) {
    try {
      const currentFormData = await formRenderRef.value.getFormData()
      if (currentFormData && typeof currentFormData === 'object') {
        formValues.value = currentFormData
        emit('form-data-change', currentFormData)
        ElMessage.success('表单数据已刷新')
      }
    } catch (error) {
      console.error('FormDetail - 手动刷新失败:', error)
      ElMessage.error('刷新表单数据失败')
    }
  } else {
    ElMessage.warning('表单渲染器未就绪')
  }
}

// 获取表单数据
const getFormData = async () => {
  // 优先返回当前内存中的formValues，确保数据是最新的
  if (formValues.value && Object.keys(formValues.value).length > 0) {
    return formValues.value
  }
  
  // 如果formValues为空，尝试从表单渲染器获取
  if (formRenderRef.value) {
    try {
      const data = await formRenderRef.value.getFormData()
      return data
    } catch (error) {
      console.warn('FormDetail - 从渲染器获取数据失败:', error)
      return formValues.value
    }
  }
  
  return formValues.value
}

// 表单校验
const validateForm = async () => {

  
  if (!formRenderRef.value) {
    console.warn('FormDetail - 表单渲染器未就绪')
    return { valid: false, errors: ['表单渲染器未就绪'] }
  }
  
  try {
    // 尝试调用VForm3的validate方法
    if (typeof formRenderRef.value.validate === 'function') {
      const result = await formRenderRef.value.validate()
      return { valid: true, data: result }
    } else {
      // 如果没有validate方法，进行基本的数据完整性检查
      const formData = await getFormData()
      const errors = []
      
      // 检查表单schema中是否有必填字段
      if (formSchema.value && formSchema.value.widgetList) {
        for (const widget of formSchema.value.widgetList) {
          if (widget.options && widget.options.required && widget.options.required === true) {
            const fieldName = widget.options.name || widget.field
            const fieldValue = formData[fieldName]
            
            if (fieldValue === undefined || fieldValue === null || fieldValue === '') {
              errors.push(`${widget.options.label || fieldName} 是必填项`)
            }
          }
        }
      }
      
      if (errors.length > 0) {
        return { valid: false, errors }
      } else {
        return { valid: true, data: formData }
      }
    }
  } catch (error) {
    console.error('FormDetail - 表单校验失败:', error)
    return { valid: false, errors: [error.message || '表单校验失败'] }
  }
}

// 更新表单校验状态
const updateFormValidationStatus = async () => {
  try {
    const validationResult = await validateForm()
    formValidationStatus.value = {
      valid: validationResult.valid,
      errors: validationResult.errors || []
    }

  } catch (error) {
    console.error('FormDetail - 更新表单校验状态失败:', error)
    formValidationStatus.value = {
      valid: false,
      errors: ['校验状态更新失败']
    }
  }
}

// 重置表单
const resetForm = () => {
  if (props.formData?.formData) {
    formValues.value = { ...props.formData.formData }
  } else {
    formValues.value = {}
  }
  isPreviewMode.value = false
}

// 暴露方法给父组件
defineExpose({
  getFormData,
  resetForm,
  refreshFormData,
  validateForm
})

// 组件挂载时启动数据同步
onMounted(() => {

  startFormDataSync()
  
  // 初始化表单校验状态
  nextTick(() => {
    updateFormValidationStatus()
  })
})

// 组件卸载时停止数据同步
onUnmounted(() => {

  stopFormDataSync()
})
</script>

<style scoped>
.form-detail {
  padding: 20px 0;
}

.form-content {
  min-height: 400px;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.form-header h3 {
  margin: 0;
  color: #1a1a1a;
  font-size: 18px;
}

.form-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.form-validation-status {
  margin-right: 8px;
}

.form-validation-status .el-tag {
  display: flex;
  align-items: center;
  gap: 4px;
}

.form-preview {
  min-height: 300px;
}

.form-container {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
}

.form-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
  text-align: center;
}

.form-placeholder :deep(svg) {
  width: 64px;
  height: 64px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.form-placeholder p {
  margin: 0 0 20px 0;
  font-size: 16px;
}

.no-form {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
  text-align: center;
}

.no-form :deep(svg) {
  width: 64px;
  height: 64px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.no-form p {
  margin: 0;
  font-size: 16px;
}

.preview-dialog-content {
  max-height: 600px;
  overflow-y: auto;
}

/* VForm3样式覆盖 */
:deep(.v-form-render) {
  font-family: inherit;
}

:deep(.v-form-render .el-form-item) {
  margin-bottom: 18px;
}

:deep(.v-form-render .el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.v-form-render .el-input__inner) {
  border-radius: 4px;
}

:deep(.v-form-render .el-textarea__inner) {
  border-radius: 4px;
}

:deep(.v-form-render .el-select) {
  width: 100%;
}

/* 添加表单数据预览样式 */
.form-data-preview-section {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
}

.preview-title {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.preview-content {
  padding: 0;
}

.form-data-display {
  background: #fafafa;
  padding: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  color: #303133;
  white-space: pre-wrap;
  word-break: break-all;
  overflow-x: auto;
  max-height: 400px;
  overflow-y: auto;
}
</style> 